import Honey from '../../utils/honey';

const app = getApp();
const honey = new Honey();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    orderId: 0,
    user: {},
    startDate: '',
    // timeArray: ['上午', '下午'],
    timeArray: [],
    organizationTip: '选择预约机构',
    familyArray: [],
    dateTips: '请选择预约日期',
    date: '',
    time: '请选择预约时段',
    // timeIndex: '',
    toUserId: '',
    toUser: '请选择预约人信息',
    familyList: [],
    order: {},
    longitude: '',
    latitude: '',
    organizationList: '',
    organizationArray: [],
    organizationId: '',
    storeId: '',
    startTime: '', //预约日期起始时间
    endtime: '', //预约日期结束时间
    nowTime: 0, //当前选择预约时段,
    nowTimeArr: [1, 2], //预约时段数组
    organizationArrayOne: [], //机构一列数据    
    organizationArrayTwo: [], //机构二列数据
    order: '', //商品详情
    storeStartTime:'',//门店开始营业时间
    storeEndTime:'',//门店结束营业时间
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    const that = this;
    const orderId = options.id ? options.id : '';
    // const storeId = options.storeId ? options.storeId : '';
    const today = new Date();
    const a = today.setTime(today.getTime() + 24 * 60 * 60 * 1000);
    const tomorrow = `${today.getFullYear()}-${today.getMonth() + 1 }-${today.getDate()}`;
    that.setData({
      orderId: orderId,
      // storeId: storeId,
      startDate: tomorrow
    })
    that.nowTimeArrFun();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {
    this.setData({
      startTime: this.formatTime(),
      endtime: this.formatEndTime(),
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    const user = honey.checkLogin('/pages/subscribe/index?id=' + that.data.orderId, false);
    that.setData({
      user: user
    })
    wx.getLocation({
      type: 'gcj02',
      success: function(res) {
        that.setData({
            longitude: res.longitude,
            latitude: res.latitude
          }),
          that.datementData()
      },
      fail: function(e) {
        that.datementData()
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  },
  changeData: function(e) {
    const that = this;
    that.setData({
      date: e.detail.value
    })
  },
  changeTime: function(e) {
    const that = this;
    that.setData({
      timeIndex: e.detail.value,
      // time: e.detail.value,
      time: that.data.timeArray[e.detail.value]
    })
  },
  changeModeTime: function(e) {
    const that = this;
    that.setData({
      time: e.detail.value,
    })
  },
  changeFamily: function(e) {
    console.log(e)
    const that = this;
    const familyIndex = e.detail.value;
    const family = that.data.familyList[familyIndex];
    that.setData({
      toUserId: family.id,
      toUser: family.family_name
    })
  },
  saveSubscribe: function(e) {
    const that = this;
    const familyId = that.data.toUserId;
    const storeId = that.data.organizationId;
    // const timeIndex = that.data.timeIndex;
    const time = that.data.time;
    const bespeakDate = that.data.date;

    if (storeId == '') {
      honey.showMiniToast({
        title: '请选择预约机构'
      })
      return false;
    }

    if (familyId == '') {
      honey.showMiniToast({
        title: '请选择预约人'
      })
      return false;
    }
    if (storeId == '') {
      honey.showMiniToast({
        title: '请选择预约机构'
      })
      return false;
    }
    if (time == '请选择预约时段') {
      honey.showMiniToast({
        title: '请选择预约时段'
      })
      return false;
    }
    if (bespeakDate == '') {
      honey.showMiniToast({
        title: '请选择预约日期'
      })
      return false;
    }

    let realTime = that.data.time.split('-')
    
    honey.post({
      alias: 'makeDatement',
      data: {
        order_sn: that.data.orderId,
        family_id: familyId,
        shop_id: storeId,
        start_time: realTime[0],
        end_time: realTime[1],
        date: bespeakDate
      },
      success: function(res) {
        wx.redirectTo({
          url: '/pages/subscribe/success?id='+res.data.data.id,
        })
      }
    })
  },
  datementData: function() {
    const that = this;
    honey.post({
      alias: 'datementData',
      data: {
        order_sn: that.data.orderId,
        longitude: that.data.longitude,
        latitude: that.data.latitude
      },
      success: function(res) {
        if (res.data.data.familyList.length > 0) {
          const familyList = res.data.data.familyList;
          let familyArray = [];
          for (let i = 0; i < familyList.length; i++) {
            familyArray.push(`${familyList[i].relation_name}：${familyList[i].family_name}（${familyList[i].sex==1?'男':'女'}）${familyList[i].family_phone}`)
          }
          that.setData({
            familyList: familyList,
            familyArray: familyArray
          })
        } else {
          honey.confirm({
            title: '添加预约人提醒',
            content: '您还没有添加预约人信息，请先添加预约人后方可预约',
            confirmText: '去添加',
            success: function(res) {
              if (res.confirm) {
                wx.navigateTo({
                  url: '/pages/mine/myFamilyEdit',
                })
              }
            }
          })
        }
        const organizationList = res.data.data.storeList;
        let organizationArray = [];
        let organizationArrayOne = [];
        let organizationArrayTwo = [];
        let organizationArrayTwoDetail = [];
        let organizationId = '',
          organizationTip = '';
        for (let i = 0; i < organizationList.length; i++) {
          organizationArrayOne.push(organizationList[i].store_name);
          for (let j = 0; j < organizationList[i].shopList.length; j++) {
            let name = organizationList[i].shopList[j].shop_name;
            let distance = organizationList[i].shopList[j].distance;
            let storeId = organizationList[i].shopList[j].store_id;
            organizationArrayTwoDetail.push(`${name}   ${distance ? "距离:" + distance + "km" : ""}`);
          }
          organizationArrayTwo.push(organizationArrayTwoDetail)
          organizationArrayTwoDetail = [];
        }
        organizationArray = [organizationArrayOne, organizationArrayTwo[0]]
        console.log(organizationArray);

        that.setData({
          organizationArray,
          organizationList,
          organizationArrayOne,
          organizationArrayTwo,
          order: res.data.data.goods,
        })
      }
    })
  },
  //value 改变时触发 change 事件
  changeOrganization: function(e) {
    console.log(e);
    const that = this;
    const indexone = e.detail.value[0]
    const indextwo = e.detail.value[1]
    let organization = that.data.organizationList[indexone].shopList[indextwo]
    let timeArray=[];
    let storeStartTime = organization.times_smeta[0].start_time;
    let storeEndTime = organization.times_smeta[organization.times_smeta.length - 1].end_time;
    
    for (let i = 0; i < organization.times_smeta.length;i++){
      timeArray.push(`${organization.times_smeta[i].start_time}-${organization.times_smeta[i].end_time}`)
    }
    that.setData({
      organizationId: organization.id,
      organizationTip: organization.shop_name,
      time: '请选择预约时段',
      timeArray,
      storeStartTime,
      storeEndTime,
    })

  },
  //改变机构列事件
  changeColumn: function(e) {
    const that = this;
    console.log(e)
    if (e.detail.column == 0) {
      const organizationIndex = e.detail.value;
      const organizationArrayOne = that.data.organizationArrayOne;
      const organizationArrayTwo = that.data.organizationArrayTwo;
      const organizationArray = [organizationArrayOne, organizationArrayTwo[organizationIndex]]
      that.setData({
        organizationArray,
        
      })
    }
  },
  formatTime: function() {
    const date = new Date()
    date.setTime(date.getTime() + 48 * 60 * 60 * 1000);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(n => {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join('-')
  },
  formatEndTime: function() {
    const date = new Date()
    date.setTime(date.getTime() + 15 * 24 * 60 * 60 * 1000);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    return [year, month, day].map(n => {
      n = n.toString()
      return n[1] ? n : '0' + n
    }).join('-')
  },

  //预约时段改变触发事件
  changenowTime: function(e) {
    console.log(e)
    const that = this;
    that.setData({
      nowTime: e.detail.value
    })
  },

  //预约时段数组生成函数
  nowTimeArrFun: function(start = '8:00', end = '18:30') {
    const that = this;
    let startFirst;
    let startTime;
    let endTime;
    let startMin;
    let endMin;
    let nowTimeArr = [];
    if (start.length == 4) {
      startFirst = start[0]
      startTime = start[0];
      startMin = start[2] + start[3];
    } else if (start.length == 5) {
      if (start[0] == 0) {
        startFirst = start[1]
        startTime = start[1];
      } else {
        startFirst = start[0] + start[1]
        startTime = start[0] + start[1];
      }
      startMin = start[3] + start[4];
    } else {
      startTime = 8;
      startMin = '00';
    }
    if (end.length == 4) {
      endTime = end[0];
      endMin = end[2] + end[3]
    } else if (end.length == 5) {
      if (end[0] == 0) {
        endTime = end[1];
      } else {
        endTime = end[0] + end[1];
      }
      endMin = end[3] + end[4];
    } else {
      endTime = 18;
      endMin = '00';
    }
    for (let i = 0; i < endTime - startFirst; i++) {
      if (i == 0) {
        if (startMin == '00') {
          nowTimeArr.push(startTime + ':00')
          nowTimeArr.push(startTime + ':30')
          nowTimeArr.push((startTime * 1 + 1) + ':00')
        } else if (startMin < 30) {
          nowTimeArr.push(startTime + ':' + startMin)
          nowTimeArr.push(startTime + ':30')
          nowTimeArr.push((startTime * 1 + 1) + ':00')
        } else if (startMin >= 30) {
          nowTimeArr.push(startTime + ':' + startMin)
          nowTimeArr.push((startTime * 1 + 1) + ':00')
        }
        if (i == endTime - startFirst - 1) {
          if (endMin == '00') {} else if (endMin <= 30) {
            nowTimeArr.push((startTime * 1 + 1) + ':' + endMin)
          } else if (endMin > 30) {
            nowTimeArr.push((startTime * 1 + 1) + ':30')
            nowTimeArr.push((startTime * 1 + 1) + ':' + endMin)
          }
        }
        startTime = startTime * 1 + 1;
        continue;
      }
      nowTimeArr.push(startTime + ':30')
      nowTimeArr.push((startTime * 1 + 1) + ':00')
      if (i == endTime - startFirst - 1) {
        if (endMin == '00') {} else if (endMin <= 30) {
          nowTimeArr.push((startTime * 1 + 1) + ':' + endMin)
        } else if (endMin > 30) {
          nowTimeArr.push((startTime * 1 + 1) + ':30')
          nowTimeArr.push((startTime * 1 + 1) + ':' + endMin)
        }
      }
      startTime = startTime * 1 + 1;

    }
    for (let key in nowTimeArr) {
      if (nowTimeArr[key] == '14:00') {
        that.setData({
          nowTime: key
        })
      }
    }
    that.setData({
      nowTimeArr
    })
  },

  //返回首页
  toBack:function(){
   wx.switchTab({
     url: '/pages/index/index',
   })
  }

})